package ck.android.englishschool.thread;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import ck.android.englishschool.AppStatus;
import ck.android.englishschool.util.BrUtilManager;
import ck.android.englishschool.util.Const;
import ck.android.englishschool.util.JSONParser;
import ck.android.englishschool.util.ParameterUtil;
import ck.android.englishschool.vo.MemberVO;

public class RegistThread extends Thread{
	private String url;
	private ArrayList<NameValuePair> post;
	private Context context;
	private AppStatus appStatus;
	private MemberVO memberVo;
	private RegistThreadCallBack callback;
	
	public RegistThread(Context context,
			RegistThreadCallBack callback, MemberVO memberVo) {
		this.context = context;
		this.callback = callback;
		this.appStatus = (AppStatus) context.getApplicationContext();
		this.memberVo = memberVo;
	}
	
	public interface RegistThreadCallBack{
		public void OnRegistThreadCompleted(boolean isNetworkConntected, MemberVO memberVo, String message);
		public void OnRegistThreadError(String message);
	}
	
	@Override
	public void run() {
		// 통신불통상태이면
		if(!appStatus.utilm.isNetworkConnected(context)) {
			callback.OnRegistThreadCompleted(false, null, "통신 에러");
			return;
		}
		
		JSONParser jParser = new JSONParser();
		
		url = Const.MAIN_URL;
		post = ParameterUtil.getRegistPostParams(memberVo);
		
		JSONObject json = jParser.getJSONFromUrl(url, post);
		Log.i("url","url = " + url + post);
		Log.i("json","json = " + json);
		if(json == null) {
			callback.OnRegistThreadError("데이터가 없습니다.");
			return;
		}

			try {
				int result = json.getInt(Const.RESULT);
				memberVo = new MemberVO();
				//정보를 못 가져 왔을때...
				if(result == 0){
					String message = json.getString(Const.MESSAGE);
					appStatus.setMemberVo(memberVo);
					callback.OnRegistThreadError(message);
				}
				//정보를 가져 왔을때...
				else{
					String message = json.getString(Const.MESSAGE);
					JSONArray jArray = json.getJSONArray(Const.DATA);
					for(int i=0; i <jArray.length(); i++){
						JSONObject itemObject = jArray.getJSONObject(i);
						System.out.println("뭐들었어??->"+itemObject.toString());
						memberVo.setMemSeq(BrUtilManager.isNullCheck(appStatus.utilm.getStringJSONObject(itemObject, MemberVO.MEMSEQ)));
						memberVo.setUserId(BrUtilManager.isNullCheck(appStatus.utilm.getStringJSONObject(itemObject, MemberVO.USERID)));
						memberVo.setUserPass(BrUtilManager.isNullCheck(appStatus.utilm.getStringJSONObject(itemObject, MemberVO.USERPASS)));
					}
					appStatus.setMemberVo(memberVo);
					callback.OnRegistThreadCompleted(true, memberVo, message);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
	}
}
